package com.yj.auto.core.jfinal.interceptor;

import java.lang.reflect.Field;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.yj.auto.core.base.exception.AutoRuntimeException;
import com.yj.auto.core.jfinal.base.BaseController;
import com.yj.auto.core.jfinal.base.BaseService;
import com.yj.auto.core.jfinal.context.AutoServiceConfig;
import com.yj.auto.utils.ClassUtil;

/**
 * 为所有BaseController注入Service
 */
public class ServiceInterceptor implements Interceptor {

	public void intercept(final Invocation inv) {
		if (inv.getTarget() instanceof BaseController) {
			BaseController c = inv.getTarget();
			Class<? extends BaseController> cls = c.getClass();
			Field[] fields = cls.getDeclaredFields();// 查找成员变量
			for (Field field : fields) {
				try {
					if (ClassUtil.isFinal(field))
						continue;
					field.setAccessible(true);
					String name = field.getName();
					if (BaseService.class.isAssignableFrom(field.getType())) {// 是否service类型成员变量
						BaseService targetService = AutoServiceConfig.getService(name);// 获取目标Service实例
						field.set(c, targetService);// 注入目标service实例
					}
				} catch (Exception e) {
					throw new AutoRuntimeException(cls.getName() + "注入" + field.getName() + "失败", e);
				} finally {
					field.setAccessible(false);
				}
			}
		}

		inv.invoke();
	}

}
